﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordNet.Core;
using WordNet.Core.DataContract;
using WordNet.Core.ElementContracts;

namespace DataFileProvider
{
    public class IndexWordMapper:IDataMapper<IIndexWord>
    {
        IDataProvider<IIndexWord> _fpIndex;
        public IndexWordMapper(IDataProvider<IIndexWord> provider)
        {
            _fpIndex = provider;
           
        }
        public IEnumerable<IIndexWord> GetAll(POS pos)
        {
            if (pos == null)
                throw new ArgumentException();

            if (!_fpIndex.IsOpen) _fpIndex.Open();
            var content = ContentType<IIndexWord>.GetIndexContentType(pos);
            IDataSource file = _fpIndex.GetSourceForContentType(content);
            var parser = content.DataType.GetParser();
            foreach (var line in file.AllLines())
            {
                yield return parser.Parse(line);
            }
        }

        public IIndexWord GetByKey(object key)
        {
            if (key == null || !(key is IIndexWordID))
                throw new ArgumentException();
           
            IIndexWordID id = (IIndexWordID)key;
            if (!_fpIndex.IsOpen) _fpIndex.Open();

            var content = ContentType<IIndexWord>.GetIndexContentType(id.PartOfSpeech);
            IDataSource file = _fpIndex.GetSourceForContentType(content);

            String line = file.Search(id.Lemma);

            if (line == null)
                return null;

            return content.DataType.GetParser().Parse(line);
        }

        public IIndexWord GetDefinition(string query)
        {
            throw new NotImplementedException();
        }

        public IDataProvider<IIndexWord> DataProvider
        {
            get { return _fpIndex; }
        }
    }
}
